import React, { Component, } from 'react';
import { AsyncStorage, SectionList } from 'react-native';
import { StyleSheet, Text, TouchableHighlight, View, Image, } from 'react-native';
import { Switch, TextInput } from 'react-native-gesture-handler';
import InterbankTransferData from './data'
import InterbankTransferBusiness from './biz';
import { Toast, } from '../../../components';
// import myPicker from 'react-native-picke
import { FlatList } from 'react-navigation';
import PayeeUserListBusiness from '../PayeeUserList/biz';
import * as BaseActions from '../../../app/actions/base';
import DealOutSelector from '../../../app/selectors/dealOut';
import connect from '../../../app/store/connect';
import { formatTime } from '../../../commons/utils/util';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  list : {
    flexGrow:1,
    backgroundColor:'#efefef',
    width:'100%'
  },
  sectionContainer : {
    backgroundColor : '#efefef',
    paddingLeft:20,
    height:20
  },
  sectionTitle : {
    fontSize: 32,
    textAlign:'left',
    color:'#080808',
    height:20
  },
  itemContainer: {
    height: 50,
    backgroundColor:'white',
    flexDirection:'row',
    alignItems:'center',
    alignContent: 'center',
    alignSelf: 'center',
  },
  itemTitle : {
    textAlign:'left',
    marginLeft: 20,
    backgroundColor:'white'
  },
  icon: {
    width: 20,
    height: 20,
    marginTop: 2
  },
  input: {
    textAlign: 'right',
    flexGrow: 1,
    alignItems: 'center',
    marginTop: 5,
    fontSize: 14,
    // marginHorizontal: 15,
    paddingTop: 10,
    paddingBottom: 10
  },
});
@connect(DealOutSelector, BaseActions)
export default class InterbankTransfer extends Component {

  static navigationOptions = ({navigation}) => {
    let receiverType =  navigation?.state?.params?.receiverType
    let navTitle = ''
    if (navigation?.state?.params?.pageMode == 1) {
      navTitle = receiverType == 2  ? '添加收款企业' : '添加收款人'
    }else {
      navTitle = '跨行转账'
    }
    return {
        title: navTitle
    }
  };

  constructor(props) {
    super(props)
    let pageMode = props?.navigation?.state?.params?.pageMode || 0
    let callbackAction = props?.navigation?.state?.params?.callback
    let interbankTransferDataInstance = new InterbankTransferData(pageMode)
    this.interbankTransferDataInstance = interbankTransferDataInstance
    let receiverType = props?.navigation?.state?.params?.receiverType || 1
    interbankTransferDataInstance.bizData.payeeInfo.receiverType = receiverType
    interbankTransferDataInstance.refreshPageListConfig()
    this.state = {
      pageListConfig : interbankTransferDataInstance.pageListConfig,
      bizData : interbankTransferDataInstance.bizData,
      pageMode : pageMode,
      callbackAction,
      tradeEnumOptions:{},
      receiverType
    }
  }
  componentDidMount() {
    let self = this
    InterbankTransferBusiness.fetchTradeEnum((info)=>{
      let tradeOptionMap = {}
      info.forEach(element => {
        tradeOptionMap[element.label] = element
      });
      this.state.tradeEnumOptions = tradeOptionMap
      this.setState(this.state)
    })
    if (this.state.pageMode == 0) {
      /// 获取汇款人信息
      InterbankTransferBusiness.fetchPayerInfo((info)=>{
        self.state.bizData.payerInfo.accNo = info.accNo
        self.state.bizData.payerInfo.accBalance = info.balance
        self.state.bizData.payerInfo.currencyType = info.currencyType
        self.setState(self.state)
      },(error)=>{
        Toast.show({title:""+error})
      })
    }

  }
  handleItemClick() {
    this.state.itemList.push(this.state.itemList[0])
    this.setState(this.state)
  }
  bizValueWithKeyPath(key,bizDataKey) {
    if (key && bizDataKey) {
      let res = this.state.bizData[bizDataKey][key]
      return ''+res
    }
    return ''
  }
  refreshBizValueWithKeyPath(value,key,bizDataKey) {
    let res = this.state.bizData[bizDataKey]
    res[key] = value
  }
  gotoPage(pageName,params){
    this.props.navigation.navigate(pageName,params)
  }
  goBack() {
    this.props.navigation.goBack()
  }
  showSelection(item) {
    if(!item.showSelection){
      item.showSelection = true
    }else {
      item.showSelection = !item.showSelection
    }
    this.setState(this.state)
  }
  refreshPageConfig() {

    this.interbankTransferDataInstance.refreshPageListConfig()
    this.state.pageListConfig = this.interbankTransferDataInstance.pageListConfig
    this.setState(this.state)
  }
  renderItem(item,bizDataKey) {
    if (item && item.shouldShow && item.shouldShow()  == false) {
      return <View/>
    }
    let body ;
    switch (item.type) {
      case 'submit':
        {
          body = (
            <View style={{height:80}}>
              <TouchableHighlight onPress={async ()=>{
                item && item.onClick && item.onClick()
                if (this.state.pageMode == 1) {
                  PayeeUserListBusiness.doCommit(this.state.bizData.payeeInfo,(resp)=>{
                    if(resp && resp.code == 0) {
                      Toast.show({title:'添加成功： '})
                      this.goBack()
                    }
                  })
                }else {

                  InterbankTransferBusiness.doCommit(this.state.bizData,()=>{
                    console.log('TAGGG', '=========doCommit===success====')
                    const time = formatTime(new Date())
                    this.props.actions.dealOut({dealTime: time})
                    Toast.show({ title: "汇出成功" });
                    setTimeout(() => {
                      this.gotoPage('Home')
                    }, 2000);
                  },(error)=>{
                      Toast.show({ title: "汇出失败，网络错误 : " + error, });
                  })
                }

              }}>
                <View style={{borderRadius:8,backgroundColor:'#0091ff', flexGrow:1,marginTop: 20, marginBottom: 100, marginLeft:20, marginRight: 20, height:40 }}>
                  <Text style={{width:'100%',color:'#FFFFFF',textAlign:'center',fontSize:16,lineHeight:40}}>{item.title}</Text>
                </View>
              </TouchableHighlight>
            </View>
          )
        }
        break;
        case 'header':
          {
            body = (
              <View style={{height:40,backgroundColor:'#EFEFEF'}}>
                    <Text style={{width:'100%',color:'#AAAAAA',textAlign:'left',fontSize:14,lineHeight:40,marginLeft:20}}>{item.title}</Text>
              </View>
            )
          }
          break;
          case 'tip':
          {
            body = (
              <View style={{height:40,backgroundColor:'#FFFFFF'}}>
                <View style={{height:40,backgroundColor:"#EFEFEF",paddingLeft:20,paddingRight:20}}>
                    <Text style={{width:'100%',color:'#AAAAAA',textAlign:'left',fontSize:14,lineHeight:40}}>{item.title}</Text>
                </View>
              </View>
            )
          }
          break;
          case 'selection':
            console.log('TAGGG', '=========selection======')
            let currentEnumOptions = this.state.tradeEnumOptions[item.bindValue]
            let optionList = []
            if (!currentEnumOptions || !(optionList = currentEnumOptions['options']))
            break;
            let displayName ;
            optionList.forEach(option => {
              if (option.keyInt == this.bizValueWithKeyPath(item.bindValue,bizDataKey)) {
                displayName = option.value
              }
            });
            console.log('TAGGG', '=========optionList======' + JSON.stringify(optionList))
            body = (
              <View style={{display:'flex',flexDirection:'column'}}>
                <View style={styles.itemContainer}>
                  <Text style={styles.itemTitle}>{item.title}</Text>
                  <View style={{flexGrow:1}}></View>
                  <TouchableHighlight  onPress={()=>{
                    this.showSelection(item)
                  }}>
                    <View style={{flexDirection:'row'}}>
                    <Text>{displayName}</Text>
                    {
                    item.showArrow ? <Image resizeMode="contain" style={styles.icon} source={{ uri: 'http://120.48.109.211:8088/static/icon/right.png', }} />
                    : null
                    }
                    </View>
                  </TouchableHighlight>

                  <View style={{width:20,opacity:1}}></View>
                </View>
                {
                  (item.showSelection == true) ?
                   <View style={{flexDirection:'column',justifyContent:'center'}} >
                     {/* <Text style={{width:'100%',textAlign:'center' , height:20,marginBottom:10}}>点击选择</Text> */}
                     <FlatList
                               bounces={false}
                               keyExtractor={item=>item.keyInt}
                               data={optionList}
                              //  style={{maxHeight:60}}
                               renderItem={(input)=>{
                                 let option = input.item
                                 return ( <View style={{height:30,flexDirection:'column',justifyContent:'center'}}>
                                           <TouchableHighlight style={{marginTop:5 , marginBottom:5 , height:20,width:'100%'}}
                                           onPress={()=>{
                                             item.showSelection = false
                                            this.refreshBizValueWithKeyPath(option.keyInt,item.bindValue,bizDataKey)
                                            this.refreshPageConfig()
                                          }}>
                                             <Text style={{lineHeight:20 , width:'100%' , textAlign:'center'}}>
                                               {option.value}
                                             </Text>
                                           </TouchableHighlight>
                                           <View style={{height:0.6, width:'auto',backgroundColor:'#C5C5C5',marginLeft:20,marginRight:20}}></View>
                                 </View>)
                               }}
                  >
                    </FlatList>
                   </View>
                   : null
                    }
              </View>

            )
            break;
      default:
        console.log('TAGGG', '=========default======')
        {
          body = ( <View style={styles.itemContainer}>
            <Text style={styles.itemTitle}>{item.title}</Text>
            {
              (item.showSwitch && item.showSwitch == true) ? <View style={{flexGrow:1}}/> : null
            }
             {
               (item.showSwitch && item.showSwitch == true) ?
               <Switch value={item.value()} style={{alignSelf:'flex-end', marginBottom: 10,}} onValueChange={(value)=>{
                 item.onSwitchChanged(value,this)
               }}></Switch> :
                (
                  (item.tapAction) ?
                  <TouchableHighlight style={{flexGrow:1}} onPress={()=>{
                    item.tapAction && item.tapAction(this)
                  }}>
                    <Text style={{ textAlign:'right', flexGrow: 1, fontSize: 14,  marginTop: 15}}>
                    {item.displayFilter?item.displayFilter(this.bizValueWithKeyPath(item.bindValue,bizDataKey)) :
                     this.bizValueWithKeyPath(item.bindValue,bizDataKey)}
                    </Text>
                  </TouchableHighlight>
                  :
                  <TextInput
                  editable={(item.editable && item.editable == false) ? false : true}
                  value={item.displayFilter?item.displayFilter(this.bizValueWithKeyPath(item.bindValue,bizDataKey)) : this.bizValueWithKeyPath(item.bindValue,bizDataKey)}
                  allowFontScaling={false}
                  onChangeText={(result_text) => {
                    this.refreshBizValueWithKeyPath(result_text,item.bindValue,bizDataKey)
                    this.setState(this.state)
                  }}
                  onEndEditing={()=>{
                    item.onValueChaneds && item.onValueChaneds(this.bizValueWithKeyPath(item.bindValue,bizDataKey),this)
                  }}
                  autoCapitalize={"none"}
                  autoCorrect={false}
                  placeholderTextColor={'#999999'}
                  placeholder={item.placeholder}
                  style={styles.input} />
                )
             }
             {
               item.tailIcon ? <TouchableHighlight onPress={()=>{
                 item.tailTapAction && item.tailTapAction(this)
               }}>
                <Image resizeMode="contain" style={styles.icon} source={{ uri: 'http://120.48.109.211:8088/static/icon/shoukuan.png', }} />
                 {/* <Icon name={item.tailIcon} size={22} color="#00aaef"/> */}
                 </TouchableHighlight>  : <View/>
             }
              {
               item.showArrow ? <TouchableHighlight onPress={()=>{
                item.tapAction && item.tapAction(this)
              }}>
                 <Image resizeMode="contain" style={styles.icon} source={{ uri: 'http://120.48.109.211:8088/static/icon/right.png', }} />
                 {/* <Icon name='chevron-right' style={{fontWeight:100}} size={18} color="#000000"/> */}
               </TouchableHighlight>   : <View/>
             }
             <View style={{width:20,opacity:1}}></View>
          </View>)
        }
        break;
    }

    return (
      <View style={{display:'flex',flexDirection:'column'}}>
          {body}
          <View style={{width:'100%',backgroundColor:'#efefef',height:1}}/>
      </View>
    )
  }
  render() {
    return (
      <View style={styles.container}>
          <SectionList style={styles.list}
          keyboardDismissMode='on-drag'
          sections={this.state.pageListConfig}
          keyExtractor={(item,index) => item + index}
          initialNumToRender={10}
          renderItem={
            ({item,section}) => (
               this.renderItem(item,section.bizDataKey)
            )
          }
          renderSectionHeader={({section:{title}})=>{
            <Text style={{fontSize:24,color:'#000000'}}>123124124</Text>
          }
        }
        />

      </View>
    );
  }
}

